package log

import (
	"os"
	_ "time"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

var L *zap.Logger

func InitLogger() {
	// 1. JSON 编码器
	enc := zapcore.NewJSONEncoder(zapcore.EncoderConfig{
		TimeKey:      "ts",
		LevelKey:     "level",
		MessageKey:   "msg",
		CallerKey:    "caller",
		EncodeTime:   zapcore.ISO8601TimeEncoder,
		EncodeLevel:  zapcore.LowercaseLevelEncoder,
		EncodeCaller: zapcore.ShortCallerEncoder,
	})

	// 2. 同时输出到控制台和文件（带切割）
	console := zapcore.AddSync(os.Stdout)
	file := zapcore.AddSync(&lumberjack.Logger{
		Filename:   "./log/app.log",
		MaxSize:    10, // MB
		MaxBackups: 3,
		MaxAge:     7, // days
	})

	// 3. 合并输出
	core := zapcore.NewTee(
		zapcore.NewCore(enc, console, zapcore.DebugLevel),
		zapcore.NewCore(enc, file, zapcore.DebugLevel),
	)

	L = zap.New(core, zap.AddCaller())
}
